//
//  InputNoViewController.swift
//  MyOfO
//
//  Created by Yuri on 2018/3/28.
//  Copyright © 2018年 Yuri. All rights reserved.
//

import UIKit
import APNumberPad
import MIBlurPopup
import FTIndicator

class InputNoViewController: UIViewController, APNumberPadDelegate, UITextFieldDelegate {

    @IBOutlet weak var inputText: UITextField!
    @IBOutlet weak var torchBtn: UIButton!
    @IBOutlet weak var voiceBtn: UIButton!
    @IBOutlet weak var confirmBtn: UIButton!
    
    var isTorchOn = false
    var isVoiceOn = true
    
    var code : Int!
    var passArray : [String] = []
    
    @IBAction func torchBtnTap(_ sender: UIButton) {
        isTorchOn = !isTorchOn
        
        if isTorchOn {
            torchBtn.setImage(#imageLiteral(resourceName: "btn_enableTorch"), for: .normal)
        } else {
            torchBtn.setImage(#imageLiteral(resourceName: "btn_unenableTorch"), for: .normal)
        }
        
        Utils.turnTorch()
    }
    
    @IBAction func voiceBtnTap(_ sender: UIButton) {
        isVoiceOn = !isVoiceOn
        
        if isVoiceOn {
            voiceBtn.setImage(#imageLiteral(resourceName: "voiceopen"), for: .normal)
        } else {
            voiceBtn.setImage(#imageLiteral(resourceName: "voiceclose"), for: .normal)
        }
        
        UserDefaults.standard.set(isVoiceOn, forKey: "isVoiceOn")
    }
    
    @IBAction func confirmBtnTap(_ sender: UIButton) {
        print("click confirm btn")
        attemptGetPasscode()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "输入车牌号"

        inputText.layer.borderWidth = 1
        inputText.layer.borderColor = UIColor.ofo.cgColor
        
        //使用第三方自定义数字键盘
        let numberPad = APNumberPad(delegate: self)
        numberPad.leftFunctionButton.setTitle("确定", for: .normal)
        inputText.inputView = numberPad
        
        inputText.delegate = self
        
        confirmBtn.isEnabled = false
        
        isVoiceOn = UserDefaults.standard.bool(forKey: "isVoiceOn")
        if isVoiceOn {
            voiceBtn.setImage(#imageLiteral(resourceName: "voiceopen"), for: .normal)
        } else {
            voiceBtn.setImage(#imageLiteral(resourceName: "voiceclose"), for: .normal)
        }
    }
    
    //点击了键盘的完成按钮
    func numberPad(_ numberPad: APNumberPad, functionButtonAction functionButton: UIButton, textInput: UIResponder & UITextInput) {
        print("click confirm button")
        
        attemptGetPasscode()
    }
    
    func attemptGetPasscode() {
        if !(inputText.text?.isEmpty)! {
            code = Int(inputText.text!)
            getPasscode()
        } else {
            FTIndicator.showToastMessage("车牌号不能为空")
        }
    }
    
    func getPasscode() {
        let query = AVQuery(className: "Code")
        query.whereKey("code", equalTo: code)
        
        query.getFirstObjectInBackground { (result, error) in
            if let e = error {
                print(e)
                self.showPopupView()
                return
            }
            
            if let code = result, let pass = result!["passcode"] as? String {
                print("passcode:\(pass)")
                var passArray : [String] = []
                passArray = pass.characters.map({
                    return $0.description
                })
                
                self.showPasscodeViewControl(array: passArray)
                
            } else {
                self.showPopupView()
            }
        }
    }
    
    func showPasscodeViewControl(array:[String]) {
        passArray = array
        performSegue(withIdentifier: "showPasscode", sender: self)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return true }
        
        let newLength = text.count + string.count - range.length
        
        if newLength > 0 {
            confirmBtn.setImage(#imageLiteral(resourceName: "nextArrow_enable"), for: .normal)
            confirmBtn.backgroundColor = UIColor.ofo
            confirmBtn.isEnabled = true
        } else {
            confirmBtn.setImage(#imageLiteral(resourceName: "nextArrow_unenable"), for: .normal)
            confirmBtn.isEnabled = false
            confirmBtn.backgroundColor = UIColor.groupTableViewBackground
        }
        //长度限制为8
        return newLength <= 8
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        if segue.identifier == "showPasscode" {
            let destSegue = segue.destination as! UnLockViewController
            destSegue.passArray = passArray
        }
        
    }
    
    func showPopupView() {
        let popupViewControl = storyboard?.instantiateViewController(withIdentifier: "SBID_POPUP_VIEW")
        MIBlurPopup.show(popupViewControl!, on: self)
    }
    

}
